<?php
namespace Lib;

use Closure;

/**
 * 用来判断php进程运行状态的
 * @package Lib
 */
class PidFile {
    private $_file;
    private $_running = false;
    private $_prevPid;
    private $callback;//绑定析构函数

    /**
     * PidFile constructor.
     * @param $dir
     * @param $name
     */
    public function __construct($dir, $name) {
        $this->_file = $dir.DIRECTORY_SEPARATOR.$name.".pid";
        if (file_exists($this->_file)) {
            $this->_prevPid = trim(file_get_contents($this->_file));
            if (isset($this->_prevPid) and self::isRunning($this->_prevPid)) {
                $this->_running = true;
            }
        }
        if (! $this->_running) {//如果上次的进程已经结束了，将本次的pid写入文件中
            $pid = getmypid();
            file_put_contents($this->_file, $pid);
        }
    }

    /**
     * 判断指定进程是否在运行
     * @param $pid
     * @return bool
     */
    public static function isRunning($pid) {
        $isRunning = false;
        if(strncasecmp(PHP_OS, "win", 3) == 0) {
            $out = [];
            exec("TASKLIST /FO LIST /FI \"PID eq $pid\"", $out);
            if(count($out) > 1) {
                $isRunning = true;
            }
        }elseif(\posix_kill(intval($pid), 0)) {
            $isRunning = true;
        }
        return $isRunning;
    }

    /**
     * 程序结束后，删除对应的id
     */
    public function __destruct() {
        if ((! $this->_running) && file_exists($this->_file)) {
            unlink($this->_file);
        }
    }

    /**
     * 上次运行的进程id是否还在运行
     * @return bool
     */
    public function isPrevRunning() {
        return $this->_running;
    }

    /**
     * 获取上次运行的pid
     * 这个进程可能会因为PHP异常结束，进程结束但pid文件还存在
     */
    public function getPrevPid(){
        return $this->_prevPid;
    }

    /**
     * 获取进程存储问题就地址
     * @return string
     */
    public function getFile(){
        return $this->_file;
    }
}